package net.qqxh.webSocket;

import com.google.gson.Gson;
import net.qqxh.persistent.JfUserSimple;
import net.qqxh.service.FileService;

import net.qqxh.service.common.BaseCallBack;
import net.qqxh.service.task.FileResolveTaskCallBack;
import net.qqxh.webSocket.config.SpringWebSocketConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author 18060774
 */
@ServerEndpoint(value = "/jfileSocketServer/{sid}" ,configurator = SpringWebSocketConfig.class)
@Component
public class JfileSocketServer  {
    private final static Logger logger = LoggerFactory.getLogger(JfileSocketServer.class);

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<JfileSocketServer> webSocketSet = new CopyOnWriteArraySet<JfileSocketServer>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;


    private static FileService fileService;
    //接收sid
    private String sid = "";
    @Autowired
    public void setFileService(FileService fileService) {
        JfileSocketServer.fileService = fileService;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        this.sid = sid;
        // sendMessage("连接成功");
       final Gson gson = new Gson();
        JfUserSimple jfUserSimple =(JfUserSimple) session.getUserProperties().get("user");
        if("1".equals(sid)) {
            /*文件处理*/
            try {
                fileService.resolveAllFile(jfUserSimple.getSearchLib(),new FileResolveTaskCallBack() {
                    @Override
                    public void doCallBack(Map<String, String> msg) {
                        try {
                            sendMessage(gson.toJson(msg));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if("2".equals(sid)) {
            fileService.cleanupViewFile(jfUserSimple.getSearchLib(),new BaseCallBack() {
                @Override
                public void doCallBack(Map<String, String> msg) {
                    try {
                        sendMessage(gson.toJson(msg));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public  void onMessage(String message, Session session) {

        //群发消息
        for (JfileSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        synchronized(this.session){
            if(this.session.isOpen()){
                /*使用异步发送消息的方法*/
                this.session.getBasicRemote().sendText(message);
            }else {
                logger.info("链接已经关闭，后台静默执行;");
            }
        }

    }


    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {

        for (JfileSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的，为null则全部推送
                if (sid == null) {
                    item.sendMessage(message);
                } else if (item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        JfileSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        JfileSocketServer.onlineCount--;
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }
    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }
}